//
//  IFAudioPlayerManager.m
//  IfengNews
//
//  Created by lihongdan on 14-7-9.
//
//

#import "IFAudioPlayerManager.h"

#import "IFPlayAudioWindow.h"
#import "SgrWeakTarget.h"
#import "IFAudioView.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import "CLAudioWindow.h"

@interface IFAudioPlayerManager ()


@property (nonatomic,strong) IFPlayAudioWindow *audioWindow;
@property (nonatomic,strong)NSTimer *timer;
@property (nonatomic,strong) CLAudioWindow *audioStatusWindow;
@property (nonatomic,strong)NSString *titlestr;



@end

@implementation IFAudioPlayerManager



- (instancetype)init{
    
    self=[super init];
    if(self){
        NSError *error=nil;
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
        [[AVAudioSession sharedInstance] setActive:YES error:&error];
        
      
        
        
       
    }
    return self;
    
    
}

+ (IFAudioPlayerManager *) shareInstance{
    static dispatch_once_t once;
    static IFAudioPlayerManager * __singletion;
    dispatch_once(&once,^{__singletion = [[IFAudioPlayerManager alloc] init];});
    return __singletion;
}


- (void)dealloc{
    if(self.player){
        [self.player stop];
    }
    
}

- (NSString *)formatSecond:(float)second{
    int x=(int)second;
    int miu=x/60;
    int sec=x%60;
    
    return [NSString stringWithFormat:@"%@%d:%@%d",(miu>9)?@"":@"0",miu,(sec>9)?@"":@"0",sec];
}

- (void)openAudioWindow{
    if(!self.audioWindow){
        self.audioWindow=[[IFPlayAudioWindow alloc] init];
        self.audioWindow.frame=CGRectMake(0.f, GlobleHeight-64.f, GlobleWidth, 64.f);
       // [[DispatchCenter listController].view addSubview:self.audioWindow];
    }else{
        [self.audioWindow checkStatus];
    }
   
}

- (void)openAudioWindowWith:(NSString *)title ItemId:(NSString *)itemId{
    
    if(!self.audioStatusWindow){
    self.audioStatusWindow=[[CLAudioWindow alloc] init];
    self.audioStatusWindow.frame=CGRectMake(0, GlobleHeight-20.f, GlobleWidth, 20.f);
    self.audioStatusWindow.windowLevel=UIWindowLevelAlert;
    [self.audioStatusWindow makeKeyAndVisible];
    }
    self.titlestr=title;
    
    [self.audioStatusWindow openAudioWindowWith:title ItemId:itemId];
    
}

-(void)closeAudioStateWindow{
    if(self.audioStatusWindow){
        [self.audioStatusWindow removeFromSuperview];
        self.audioStatusWindow=nil;
    }
}

- (void)hiddenStateWindow{
    self.audioStatusWindow.hidden=YES;
}

- (void)notHiddenStateWindwo{
    self.audioStatusWindow.hidden=NO;
}

- (void)closeAudioWindow{
    if(self.audioWindow){
        [self.audioWindow removeFromSuperview];
        self.audioWindow=nil;
    }
}


- (void)resumeOrPause{
    if(!self.player) return;
    
    if(self.player.state==STKAudioPlayerStatePaused){
        [self.player resume];
    }else{
        [self.player pause];
    }
    
}

- (void)pause{
    [self.player pause];
    [self closeAudioStateWindow];
}

- (void)resume{
    [self.player resume];
    [self openAudioWindowWith:self.titlestr ItemId:self.tag];
}


- (void)play{
    [self.player play:self.audioUrl];
    
    NSString *title=nil;
    if(self.delegate2 && [self.delegate2 respondsToSelector:@selector(getAudioTitle)]){
        title=[self.delegate2 getAudioTitle];
    }
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(getAudioTitle)]){
        title=[self.delegate getAudioTitle];
    }
    
    [self openAudioWindowWith:title ItemId:self.tag];
}



- (void)remoteControlReceivedWithEvent:(UIEvent *)event{
    if(!self.player) return;
    
    
    if (event.type == UIEventTypeRemoteControl){
        switch (event.subtype) {
            case UIEventSubtypeRemoteControlTogglePlayPause:
                [self resumeOrPause]; // 切换播放、暂停按钮
                break;
                
     
                
			case UIEventSubtypeRemoteControlPause: // 暂停
				[self.player pause];
				break;
                
			case UIEventSubtypeRemoteControlPlay: // 播放
                [self.player resume];
				break;
                
            default:
                break;

        }
        
        if(self.delegate && [self.delegate respondsToSelector:@selector(audioRemoteControlReceivedWithEvent:)]){
            [self.delegate performSelector:@selector(audioRemoteControlReceivedWithEvent:) withObject:event];
        }
        
        if(self.delegate2 && [self.delegate2 respondsToSelector:@selector(audioRemoteControlReceivedWithEvent:)]){
            [self.delegate2 performSelector:@selector(audioRemoteControlReceivedWithEvent:) withObject:event];
        }

    }
    
}

-(void) seekToTime:(double)value{
    [self.player seekToTime:value];
}

- (BOOL)isPlaying{
    return self.player!=nil;
}

- (BOOL)isPause{
    return [self isPlaying] && self.player.state==STKAudioPlayerStatePaused;
}

- (BOOL)isRunning{
    return [self isPlaying] && self.player.state==STKAudioPlayerStatePlaying;
}

- (BOOL)isStop{
    return [self isPlaying] && self.player.state==STKAudioPlayerStateStopped;
}

//- (BOOL)isFinish{
//    self.player.state
//}

- (STKAudioPlayer *)createPlayer{
    
 
    
    if(!self.player){
        self.player=[[STKAudioPlayer alloc] init];
        
        
        
        self.player.delegate=self;
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    }
    
    return self.player;
}


- (void)startTimer{
    if(!self.timer){
        
        
        SgrWeakTarget *target=[[SgrWeakTarget alloc] init];
        target.obj=self;
        target.select=@selector(checkProgress);
     
        self.timer=[NSTimer scheduledTimerWithTimeInterval:0.3 target:target selector:@selector(perform) userInfo:nil repeats:YES];

        
      
    }
}


- (void)checkProgress{
    if(_delegate && [_delegate respondsToSelector:@selector(audioProgerss:)]){
        [_delegate audioProgerss:self.player.progress];
    }
    
    if(_delegate2 && [_delegate2 respondsToSelector:@selector(audioProgerss:)]){
        [_delegate2 audioProgerss:self.player.progress];
    }
}


- (void)setiPodAudioInfo:(UIImage *)coverImage andTitle:(NSString *)audioTitle andArtist:(NSString *)artist withTimeSize:(NSInteger)timeSize
{
	
	if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
		NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
		
		if(audioTitle != nil) {
			[dict setObject:audioTitle forKey:MPMediaItemPropertyTitle];
			[dict setObject:artist forKey:MPMediaItemPropertyAlbumTitle];
		} else {
			[dict setObject:@"正在收听：禅林" forKey:MPMediaItemPropertyTitle];
			[dict setObject:@"禅林" forKey:MPMediaItemPropertyAlbumTitle];
		}
        
        
        //		[dict setObject:[NSNumber numberWithInt:timeSize] forKey:MPMediaItemPropertyPlaybackDuration];
        //		[dict setObject:[NSNumber numberWithDouble:1.f] forKey:MPNowPlayingInfoPropertyPlaybackRate];
        
        
		if(coverImage) {
            MPMediaItemArtwork * mArt = [[MPMediaItemArtwork alloc] initWithImage:coverImage];
            [dict setObject:mArt forKey:MPMediaItemPropertyArtwork];
		}
		[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
		[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
	}
}



#pragma mark - iPod管理功能方法

- (void)checkRegister{
    if([self isPlaying]){
        [self registeiPod:[UIApplication sharedApplication].delegate];
    }else{
        [self unRegisteiPod:[UIApplication sharedApplication].delegate];
    }
}


//注册iPod功能
- (void)registeiPod:(UIResponder*)responder
{
   
    
	UIDevice* device = [UIDevice currentDevice];
	BOOL bcSupport = NO;
	if([device respondsToSelector:@selector(isMultitaskingSupported)]) {
		bcSupport = device.multitaskingSupported;
	}
	
	if(bcSupport) {
		[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
		[responder becomeFirstResponder];
	}
}

//注销iPod功能
- (void)unRegisteiPod:(UIResponder*)responder
{
	[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
	[responder resignFirstResponder];
}


- (void)playWithURLString:(NSString *)url{
     [self createPlayer];
    self.audioUrl=url;
    [self closeAudioWindow];
    [self.player play:url];
    [self registeiPod:[UIApplication sharedApplication].delegate];
    [self setiPodAudioInfo:nil andTitle:@"禅林" andArtist:@"" withTimeSize:0];
}

- (void)playWithURLString:(NSString *)url title:(NSString *)title{
    [self createPlayer];
    self.audioUrl=url;
    [self closeAudioWindow];
    

    [self openAudioWindowWith:title ItemId:self.tag];

    
    [self.player play:url];
    [self registeiPod:[UIApplication sharedApplication].delegate];
    [self setiPodAudioInfo:nil andTitle:title andArtist:@"" withTimeSize:0];
}

- (void)stop{
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(willStop:)]){
        [self.delegate willStop:self.tag];
    }
    
    if(self.delegate2 && [self.delegate2 respondsToSelector:@selector(willStop:)]){
        [self.delegate2 willStop:self.tag];
    }
    
    if(self.player){
        [self.player stop];
        self.player.delegate=nil;
        self.player=nil;
        self.tag=nil;
        
    }
    if(self.timer){
        [self.timer invalidate];
        self.timer=nil;
    }
    [self closeAudioWindow];
    [self closeAudioStateWindow];
    [self unRegisteiPod:[UIApplication sharedApplication].delegate];
}

/// Raised when an item has started playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId{
   
}
/// Raised when an item has finished buffering (may or may not be the currently playing item)
/// This event may be raised multiple times for the same item if seek is invoked on the player
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId{
    
}
/// Raised when the state of the player has changed
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState{
    if(state==STKAudioPlayerStatePlaying){
        [self startTimer];
        if(self.delegate && [self.delegate respondsToSelector:@selector(playingStstusTotalTime:current:)]){
            [self.delegate playingStstusTotalTime:audioPlayer.duration current:audioPlayer.progress];
            
        }
        if(self.delegate2 && [self.delegate2 respondsToSelector:@selector(playingStstusTotalTime:current:)]){
            [self.delegate2 playingStstusTotalTime:audioPlayer.duration current:audioPlayer.progress];
            
        }

    }else if(state == STKAudioPlayerStatePaused){
        if(self.delegate && [self.delegate respondsToSelector:@selector(willpause:)]){
            [self.delegate willpause:self.tag];
            
        }
        if(self.delegate2 && [self.delegate2 respondsToSelector:@selector(willpause:)]){
            [self.delegate2 willpause:self.tag];
            
        }

    }
    
    
}
/// Raised when an item has finished playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration{
   
    if(self.delegate && [self.delegate respondsToSelector:@selector(finishwithReason: andProgress: andDuration:)]){
        [self.delegate finishwithReason:stopReason andProgress:progress andDuration:duration];
    }
    if(self.delegate2 && [self.delegate2 respondsToSelector:@selector(playingStstusTotalTime:current:)]){
        //[self.delegate2 playingStstusTotalTime:audioPlayer.duration current:audioPlayer.progress];
        [self.delegate2 finishwithReason:stopReason andProgress:progress andDuration:duration];
        
    }

    
}
/// Raised when an unexpected and possibly unrecoverable error has occured (usually best to recreate the STKAudioPlauyer)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode{
  
}




@end
